<?php

namespace App\Libs\Pay;

use Phalcon\Config\Adapter\Ini as ConfigIni;
use \App\Libs\Base\Config;

class PayLibs extends \App\Libs\Base\Singleton
{
    protected $aopClient;

    /**
     * PayLibs constructor.
     * @param $type 1:alipay  2:weixin   3:pailebao
     * @param bool $check 是否是验证
     */
    public function __construct($type, $check = false)
    {
        switch ($type) {
            //支付宝
            case 1:
                require __DIR__ . '/Alipay/AopSdk.php';
                $this->aopClient = new \AopClient();
                //支付参数
                $alipayInfo = Config::instance()->pay['alipay'];
                if (!$check) {
                    $this->aopClient->appId = $alipayInfo['appId'];
                    $this->aopClient->rsaPrivateKey = $alipayInfo['rsaPrivateKey'];
                    $this->aopClient->signType = $alipayInfo['signType'];
                }
                $this->aopClient->alipayrsaPublicKey = $alipayInfo['alipayrsaPublicKey'];

                break;
            case 2:
                $this->weixinPay();
                break;
            case 3:
                $this->pailePay();
                break;
        }
    }

    /**
     * @param $goodsInfo   商品描述信息;
     * @param null $ConfigArraykey 在配置文件alipay中的回调键名称,默认：notify_url
     * @return array
     */
    public function getAlipayAppStr($goodsInfo, $ConfigArraykey = null)
    {
        $createReq = new \AlipayTradeAppPayRequest();
        $alipayInfo = Config::instance()->pay['alipay'];
        if ($ConfigArraykey == null) {
            $notifyUrl = 'notify_url';
        } else {
            $notifyUrl = $ConfigArraykey;
        }
        $createReq->setNotifyUrl($alipayInfo[$notifyUrl]);
        $createReq->setBizContent(json_encode($goodsInfo));
        $queryString = $this->aopClient->sdkExecute($createReq);
        return [
            'alipayStr' => $queryString
        ];
    }
    /**
     * @param $post  支付宝post的数据
     * @return bool   //验签结果
     */
    public function alipay_notify($post)
    {
        $alipayInfo = Config::instance()->pay['alipay'];
        $flag = $this->aopClient->rsaCheckV1($post, NULL, $alipayInfo['signType']);  //验证签名
        return $flag;
    }

    /**
     * @param $order_sn   本系统订单号
     * @param bool   是否直接返回相应的对象
     * @return bool
     */
    public function alipayQueryOrderStatus($order_sn, $returnObj = false)
    {
        $queryRequest = new \AlipayTradeQueryRequest();
        $data = [
            'out_trade_no' => $order_sn
        ];
        $queryRequest->setBizContent(json($data));
        $resObj = $this->aopClient->execute($queryRequest);
        $responseNode = str_replace(".", "_", $queryRequest->getApiMethodName()) . "_response";
        $resultobj = $resObj->$responseNode;
        if ($returnObj) {
            return $resultobj;
        } else {
            $resultCode = $resultobj->code;
            if (!empty($resultCode) && $resultCode == 10000) {
                return $resultobj->trade_status;
            } else {
                return false;
            }
        }

    }

    /**
     * @param array $refundInfo 数组：至少包含订单号和退款金额:
     *                      out_trade_no(本系统订单号),
     *                      refund_amount（退款金额）
     *                      trade_no（支付宝交易号）
     * @return array|\SimpleXMLElement[]
     */
    public function alipayRefund($refundInfo = [])
    {
        $refundRequest = new \AlipayTradeRefundRequest();
        $refundRequest->setBizContent(json_encode($refundInfo));
        $result = $this->aopClient->execute($refundRequest);
        $responseNode = str_replace(".", "_", $refundRequest->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if (!empty($resultCode) && $resultCode == 10000) {
            //成功
            return $result->$responseNode;
        } else {
            //失败
            if (isset($result->$responseNode->sub_msg)) {
                $returnMsg = $result->$responseNode->sub_msg;
            } else {
                $returnMsg = $result->$responseNode->msg;
            }
            return ['status' => false, 'msg' => $returnMsg];
        }

    }
}

